package com.rongshu.widget.xrichtext;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.res.ResourcesCompat;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.CharacterStyle;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.rongshu.R;
import com.rongshu.view.home.widget.SelectableTextView;
import com.utils.LogUtil;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * https://github.com/sendtion/XRichText
 * Created by sendtion on 2016/6/24.
 * 显示富文本
 */
public class RichTextView extends LinearLayout {
    private Context context;
    private int viewTagIndex = 1; // 新生的view都会打一个tag，对每个view来说，这个tag是唯一的。
    private LayoutInflater inflater;
    private OnClickListener btnListener;//图片点击事件
    private ArrayList<String> imagePaths;//图片地址集合
    private String keywords;//关键词高亮

    private OnRtImageClickListener onRtImageClickListener;
    //插入的图片显示高度
    private int rtImageHeight = 0; //为0显示原始高度
    /**
     * 自定义属性
     **/
    //图片的上下距离
    private int rtImageSpacing;
    //文字相关属性，初始提示信息，文字大小和颜色
    private int rtTextSize; //相当于16sp
    private int rtTextColor;
    private int rtTextLineSpace; //相当于8dp

    public RichTextView(Context context) {
        this(context, null);
    }

    public RichTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RichTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setOrientation(LinearLayout.VERTICAL);
        LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT);
        setLayoutParams(layoutParams);

        //获取自定义属性
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.RichTextView);
        rtImageSpacing = ta.getInteger(R.styleable.RichTextView_rt_view_image_spacing, 20);
        rtTextSize = ta.getDimensionPixelSize(R.styleable.RichTextView_rt_view_text_size, 15);
        rtTextLineSpace = ta.getDimensionPixelSize(R.styleable.RichTextView_rt_view_text_line_space, 8);
        rtTextColor = ta.getColor(R.styleable.RichTextView_rt_view_text_color, Color.parseColor("#757575"));
        ta.recycle();

        this.context = context;
        imagePaths = new ArrayList<>();
        inflater = LayoutInflater.from(context);

        btnListener = new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (v instanceof DataImageView) {
                    DataImageView imageView = (DataImageView) v;
                    // 开放图片点击接口
                    if (onRtImageClickListener != null) {
                        onRtImageClickListener.onRtImageClick(imageView.getAbsolutePath());
                    }
                }
            }
        };
    }

    public interface OnRtImageClickListener {
        void onRtImageClick(String imagePath);
    }

    public void setOnRtImageClickListener(OnRtImageClickListener onRtImageClickListener) {
        this.onRtImageClickListener = onRtImageClickListener;
    }

    public ArrayList<String> getImagePaths() {
        return imagePaths;
    }

    /**
     * 设置字体大小
     */
    public void setRtTextSize(int size) {
        this.rtTextSize = size;
    }

    /**
     * 遍历更新所有的textview
     */
    public void updateRTTextSize(int size) {
        LogUtil.d("==========>> textview收到消息" + size);
        for (int index = 0; index < getChildCount(); index++) {
            View childAt = getChildAt(index);
            if (childAt instanceof TextView) {
                TextView textView = (TextView) childAt;
                textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
            }
        }
    }

    /**
     * 清除所有的view
     */
    public void clearAllLayout() {
        removeAllViews();
    }

    /**
     * 获得最后一个子view的位置
     *
     * @return
     */
    public int getLastIndex() {
        int lastEditIndex = getChildCount();
        return lastEditIndex;
    }

    /**
     * 生成文本输入框
     */
    public SelectableTextView createTextView() {
        SelectableTextView textView = (SelectableTextView) inflater.inflate(R.layout.rich_textview, null);
        textView.setTag(viewTagIndex++);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, rtTextSize);
        textView.setLineSpacing(rtTextLineSpace, 1.0f);
        textView.setTextColor(ContextCompat.getColor(context, R.color.color_4c4c4c));
        Typeface typeFace = ResourcesCompat.getFont(getContext(), R.font.pingfang_standard);
        textView.setTypeface(typeFace);
        return textView;
    }

    /**
     * 生成图片View
     */
    private DataImageView createImageLayout() {
        DataImageView imageView = (DataImageView) inflater.inflate(R.layout.edit_imageview, null);
        imageView.setOnClickListener(btnListener);
        return imageView;
    }

    /**
     * 关键字高亮显示
     *
     * @param target 需要高亮的关键字
     * @param text   需要显示的文字
     * @return spannable 处理完后的结果，记得不要toString()，否则没有效果
     * SpannableStringBuilder textString = TextUtilTools.highlight(item.getItemName(), KnowledgeActivity.searchKey);
     * vHolder.tv_itemName_search.setText(textString);
     */
    public static SpannableStringBuilder highlight(String text, String target) {
        SpannableStringBuilder spannable = new SpannableStringBuilder(text);
        CharacterStyle span;

        Pattern p = Pattern.compile(target);
        Matcher m = p.matcher(text);
        while (m.find()) {
            span = new ForegroundColorSpan(Color.parseColor("#EE5C42"));// 需要重复！
            spannable.setSpan(span, m.start(), m.end(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return spannable;
    }

    public void setKeywords(String keywords) {
        this.keywords = keywords;
    }

    /**
     * 在特定位置插入EditText
     *
     * @param editStr EditText显示的文字
     */
    public void addTextViewAtIndex(CharSequence editStr) {
//        LogUtil.d("插入的文字: "  + editStr.toString() + ", index： " + index);
        String spanned = Html.fromHtml(editStr.toString()).toString();
        /**
         * if (!TextUtils.isEmpty(keywords)) {//搜索关键词高亮
         *             SpannableStringBuilder textStr = highlight(editStr.toString(), keywords);
         *             textView.setText(textStr);
         *         } else {
         *             textView.setText(editStr);
         *         }
         */
        /**
         * 处理段间距
         */
        String[] split = spanned.split("\n\n");
        for (int position = 0; position < split.length; position++) {
            SelectableTextView textView = createTextView();
            textView.setText(split[position].trim());
//            View view = new View(context);
//            LinearLayout.LayoutParams linearParams = new LinearLayout.LayoutParams(
//                    ViewGroup.LayoutParams.MATCH_PARENT,
//                    (int) getResources().getDimension(R.dimen.dd_dimen_60px));
//            view.setLayoutParams(linearParams);
            addView(textView, getLastIndex());
            //当前容器中不止一个textView，且textView不是最后一个view
            if (split.length != 1 && position != split.length - 1) {
                //添加距离底部的margin作为段落间距
                LinearLayout.LayoutParams params = (LayoutParams) textView.getLayoutParams();
                params.bottomMargin = (int) getResources().getDimension(R.dimen.dd_dimen_60px);
                textView.setLayoutParams(params);
                //添加一个空的view作为段间距
//                addView(view, getLastIndex());
            }
        }
    }

    /**
     * 在特定位置添加ImageView
     */
    public void addImageViewAtIndex(final String imagePath, final boolean isFirstInsert) {
        imagePaths.add(imagePath);
        final DataImageView imageView = createImageLayout();
        imageView.setAbsolutePath(imagePath);
        //如果是网络图片
        if (imagePath.startsWith("http://") || imagePath.startsWith("https://")) {
            Glide.with(getContext()).asBitmap().load(imagePath).
                    into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                            //调整imageView的高度，根据宽度等比获得高度
                            int imageHeight; //解决连续加载多张图片导致后续图片都跟第一张高度相同的问题
                            if (rtImageHeight > 0) {
                                imageHeight = rtImageHeight;
                            } else {
                                imageHeight = getWidth() * resource.getHeight() / resource.getWidth();
                            }
                            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                                    LayoutParams.MATCH_PARENT, imageHeight);//固定图片高度，记得设置裁剪剧中
                            if (!isFirstInsert) {
                                lp.topMargin = rtImageSpacing;
                            }
                            lp.bottomMargin = rtImageSpacing;
                            imageView.setLayoutParams(lp);

//                            if (rtImageHeight > 0) {
//                                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
//                            } else {
//                                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
//                            }
                            imageView.setImageBitmap(resource);
                        }
                    });
        } else { //如果图片格式异常
            Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.default_article_insert_img);
            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, (int) context.getResources().getDimension(R.dimen.dd_dimen_60px));
            imageView.setLayoutParams(lp);
            imageView.setImageBitmap(bitmap);
        }

        // onActivityResult无法触发动画，此处post处理
        addView(imageView, getLastIndex());
    }

    /**
     * 根据view的宽度，动态缩放bitmap尺寸
     *
     * @param width view的宽度
     */
    public Bitmap getScaledBitmap(String filePath, int width) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        int sampleSize = options.outWidth > width ? options.outWidth / width
                + 1 : 1;
        options.inJustDecodeBounds = false;
        options.inSampleSize = sampleSize;
        return BitmapFactory.decodeFile(filePath, options);
    }
}
